/* eslint-disable */
import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Table, Modal, message, Checkbox, Tag, Space, Layout, Switch } from 'antd';
import './test.css';
import { getAllTests, createTest, updateTest, deleteTest, searchTests, getTestsByTypes } from '../../api/TestIndex';

const { Header, Content } = Layout;

const Test = () => {
  const [listData, setListData] = useState([]);
  const [TableData, setTableData] = useState([]);
  const [modalType, setModalType] = useState(0); // 0为新增，1为编辑
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); // 新增删除确认弹窗状态
  const [currentRow, setCurrentRow] = useState(null); // 当前选中的行数据
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [activeTag, setActiveTag] = useState(null); // 当前选中的标签

  let clickCount = 0;
  let lastClickTime = null;
  let isBlocked = false;
  let blockTimer = null;

  // 新增/编辑
  const handClick = (type, rowData) => {
    setIsModalOpen(!isModalOpen);
    if (type === 'add') {
      setModalType(0);
      form.resetFields(); // 新增时重置表单
    } else {
      setModalType(1);
      const cloneData = JSON.parse(JSON.stringify(rowData));
      form.setFieldsValue(cloneData); // 表单数据回填
    }
  };

  // 提交-搜索
  const handFinish = async (values) => {
    const currentTime = Date.now();

    // 如果距离上次点击时间超过一分钟，重置计数器和时间
    if (lastClickTime && currentTime - lastClickTime > 60000) {
      clickCount = 0;
      lastClickTime = null;
      isBlocked = false;
      clearTimeout(blockTimer); // 清除之前的定时器
    }

    if (isBlocked) {
      return; // 不返回错误信息，直接返回
    }

    clickCount++;
    lastClickTime = currentTime;

    if (clickCount > 3) {
      message.error("点击次数过多，请一分钟后再试。");
      isBlocked = true;
      blockTimer = setTimeout(() => {
        isBlocked = false;
        clickCount = 0;
      }, 60000); // 60秒后解除阻止
      return;
    }

    const params = values.keyword ? { keyword: values.keyword } : {};
    try {
      const res = await searchTests(params);
      setTableData(res.data); // 假设返回的res有data属性
    } catch (error) {
      console.error("搜索失败:", error);
      message.error(`搜索失败: ${error.response?.data?.message || error.message}`);
    }
  };

  // 删除
  const handDelete = async (rowData) => {
    if (rowData.status === 1) {
      message.error("当前题目正在使用，无法删除");
      return;
    }
    setCurrentRow(rowData); // 设置当前选中的行数据
    setIsDeleteModalOpen(true); // 打开删除确认弹窗
  };

  // 确认删除
  const handleDeleteConfirm = async () => {
    try {
      await deleteTest(currentRow.id);
      getTableData(); // 删除成功后刷新列表
      setIsDeleteModalOpen(false); // 关闭删除确认弹窗
      message.success("删除成功");
    } catch (error) {
      console.error("删除失败:", error);
      message.error(`删除失败: ${error.response?.data?.message || error.message}`);
    }
  };

  // 取消删除
  const handleDeleteCancel = () => {
    setIsDeleteModalOpen(false); // 关闭删除确认弹窗
  };

  // 获取测试列表数据
  const getTableData = async (params = {}) => {
    try {
      const res = await getAllTests(params);
      setTableData(res.data); // 假设返回的res有data属性
    } catch (error) {
      console.error("获取测试数据失败:", error);
      message.error(`获取测试数据失败: ${error.response?.data?.message || error.message}`);
    }
  };

  // 在组件加载时获取所有测试数据
  useEffect(() => {
    getTableData();
  }, []);

  // 弹窗确定
  const handleOk = async () => {
    const currentTime = Date.now();

    // 如果距离上次点击时间超过一分钟，重置计数器和时间
    if (lastClickTime && currentTime - lastClickTime > 60000) {
      clickCount = 0;
      lastClickTime = null;
      isBlocked = false;
      clearTimeout(blockTimer); // 清除之前的定时器
    }

    if (isBlocked) {
      return; // 不返回错误信息，直接返回
    }

    clickCount++;
    lastClickTime = currentTime;

    if (clickCount > 3) {
      message.error("点击次数过多，请一分钟后再试。");
      isBlocked = true;
      blockTimer = setTimeout(() => {
        isBlocked = false;
        clickCount = 0;
      }, 60000); // 60秒后解除阻止
      return;
    }

    try {
      const val = await form.validateFields();
      if (modalType === 1) {
        await updateTest(val.id, val); // 传递ID和更新的数据
      } else {
        await createTest(val);
      }
      getTableData(); // 更新成功后刷新列表
      setIsModalOpen(false);
      message.success(modalType ? "更新成功" : "新增成功");
    } catch (error) {
      console.error("操作失败:", error);
      message.error(`操作失败: ${error.response?.data?.message || error.message}`);
    }
  };

  // 弹窗取消
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields(); // 清空表单数据
  };

  // 当前行数据
  const columns = [
    {
      title: '题目',
      dataIndex: 'topic',
    },
    {
      title: '类型',
      dataIndex: 'types',
      render: (types) => (
        <>
          {types.map((type) => {
            let color = '';
            let text = '';
            switch (type) {
              case 1:
                color = 'blue';
                text = '抑郁症';
                break;
              case 2:
                color = 'green';
                text = '双相情感障碍';
                break;
              case 3:
                color = 'red';
                text = '焦虑';
                break;
              case 4:
                color = 'magenta';
                text = '自闭症';
                break;
              case 5:
                color = 'geekblue';
                text = '成瘾';
                break;
              case 6:
                color = 'cyan';
                text = '多动症';
                break;
              case 7:
                color = 'gold';
                text = '人格障碍';
                break;
              case 8:
                color = 'purple';
                text = '精神分裂';
                break;
              case 9:
                color = 'lime';
                text = '进食障碍';
                break;
              case 10:
                color = 'error';
                text = '强迫症';
                break;
              case 11:
                color = 'processing';
                text = '创伤后应激障碍';
                break;
              default:
                color = 'orange';
                text = '性功能障碍';
            }
            return <Tag color={color} key={type} style={{ width: '100px', textAlign: 'center' }}>{text}</Tag>;
          })}
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => (
        <Switch
          checked={status === 1} // 如果状态为1，开关为开
          disabled={status === 1} // 如果状态为1，开关不可点击
        />
      ),
    },
    {
      title: '操作',
      render: (rowData) => {
        return (
          <div className='flex-box'>
            <Button style={{ marginRight: '5px' }} onClick={() => { handClick('edit', rowData) }}>编辑</Button>
            <Button type='primary' danger onClick={() => { handDelete(rowData) }}>删除</Button>
          </div>
        );
      }
    },
  ];

  // 处理标签点击
  const handleTagClick = async (type) => {
    setActiveTag(type);
    try {
      if (type === null) {
        await getTableData();
      } else {
        const response = await getTestsByTypes([type]);
        setTableData(response.data);
      }
    } catch (error) {
      console.error("获取分类数据失败:", error);
      message.error(`获取分类数据失败: ${error.response?.data?.message || error.message}`);
    }
  };

  return (
    <Layout style={{ background: '#f0f2f5' }}>
      <Header style={{ backgroundColor: '#fff', padding: '0 24px', borderBottom: '1px solid #f0f0f0' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '20px' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Form
              layout='inline'
              onFinish={handFinish}
              form={searchForm}
              onValuesChange={(changedValues, allValues) => {
                if (!allValues.keyword) {
                  getTableData();
                }
              }}
            >
              <Form.Item name='keyword'>
                <Input placeholder='请输入关键词' style={{ height: '35px' }} />
              </Form.Item>
              <Form.Item>
                <Button type='primary' htmlType='submit'>搜索</Button>
              </Form.Item>
            </Form>
          </div>
          <Button type='primary' onClick={() => { handClick('add') }}>新增</Button>
        </div>
      </Header>
      <Content >
        {/* 分类标签行 */}
        <div style={{ textAlign: 'center', backgroundColor: '#fff', height: "40px " }}>
          <span style={{ marginRight: '10px', fontWeight: 'bold' }}>试题类型：</span>
          <Space size={8}>
            <Tag
              color={activeTag === null ? 'volcano' : 'default'}
              onClick={() => handleTagClick(null)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              全部
            </Tag>
            <Tag
              color={activeTag === 1 ? 'blue' : 'default'}
              onClick={() => handleTagClick(1)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              抑郁症
            </Tag>
            <Tag
              color={activeTag === 2 ? 'green' : 'default'}
              onClick={() => handleTagClick(2)}
              style={{ cursor: 'pointer', width: '90px', textAlign: 'center', marginTop: '10px' }}
            >
              双相情感障碍
            </Tag>
            <Tag
              color={activeTag === 3 ? 'red' : 'default'}
              onClick={() => handleTagClick(3)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              焦虑
            </Tag>
            <Tag
              color={activeTag === 4 ? 'magenta' : 'default'}
              onClick={() => handleTagClick(4)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              自闭症
            </Tag>
            <Tag
              color={activeTag === 5 ? 'geekblue' : 'default'}
              onClick={() => handleTagClick(5)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              成瘾
            </Tag>
            <Tag
              color={activeTag === 6 ? 'cyan' : 'default'}
              onClick={() => handleTagClick(6)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              多动症
            </Tag>
            <Tag
              color={activeTag === 7 ? 'gold' : 'default'}
              onClick={() => handleTagClick(7)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              人格障碍
            </Tag>
            <Tag
              color={activeTag === 8 ? 'purple' : 'default'}
              onClick={() => handleTagClick(8)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              精神分裂
            </Tag>
            <Tag
              color={activeTag === 9 ? 'lime' : 'default'}
              onClick={() => handleTagClick(9)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              进食障碍
            </Tag>
            <Tag
              color={activeTag === 10 ? 'error' : 'default'}
              onClick={() => handleTagClick(10)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              强迫症
            </Tag>
            <Tag
              color={activeTag === 11 ? 'processing' : 'default'}
              onClick={() => handleTagClick(11)}
              style={{ cursor: 'pointer', width: '100px', textAlign: 'center', marginTop: '10px' }}
            >
              创伤后应激障碍
            </Tag>
            <Tag
              color={activeTag === 12 ? 'orange' : 'default'}
              onClick={() => handleTagClick(12)}
              style={{ cursor: 'pointer', width: '80px', textAlign: 'center', marginTop: '10px' }}
            >
              性功能障碍
            </Tag>
          </Space>
        </div>

        <Table
          style={{ marginTop: '20px' }}
          columns={columns}
          dataSource={TableData}
          rowKey={'id'}
        />
      </Content>
      <Modal
        open={isModalOpen}
        title={modalType ? '编辑信息' : '新增信息'}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 14 }}
          labelAlign='left'
        >
          {modalType === 1 && (
            <Form.Item
              label="试题号"
              name="id"
              rules={[
                {
                  required: true,
                  message: '请输入试题号'
                },
                {
                  validator: (_, value) => {
                    if (!value) {
                      return Promise.reject('试题号不能为空');
                    }
                    if (isNaN(value)) {
                      return Promise.reject('试题号必须为数字！');
                    }
                    return Promise.resolve();
                  }
                }
              ]}
            >
              <Input placeholder='请输入试题号' maxLength={10} disabled={modalType === 1} />
            </Form.Item>
          )}
          <Form.Item
            label="题目"
            name="topic"
            rules={[
              {
                required: true,
                message: '请输入题目'
              },
              {
                max: 50,
                message: '题目不能超过50个字符'
              }
            ]}
          >
            <Input placeholder='请输入题目' maxLength={50}
              onChange={(e) => {
                if (e.target.value.length >= 50) {
                  message.warning('题目不能超过50个字符');
                }
              }}
            />
          </Form.Item>
          <Form.Item
            label="类型"
            name="types"
            rules={[
              {
                required: true,
                message: '请选择类型'
              }
            ]}
          >
            <Checkbox.Group>
              <Checkbox value={1}>抑郁症</Checkbox>
              <Checkbox value={2}>双相情感障碍</Checkbox>
              <Checkbox value={3}>焦虑</Checkbox>
              <Checkbox value={4}>自闭症</Checkbox>
              <Checkbox value={5}>成瘾</Checkbox>
              <Checkbox value={6}>多动症</Checkbox>
              <Checkbox value={7}>人格障碍</Checkbox>
              <Checkbox value={8}>精神分裂</Checkbox>
              <Checkbox value={9}>进食障碍</Checkbox>
              <Checkbox value={10}>强迫症</Checkbox>
              <Checkbox value={11}>创伤后应激障碍</Checkbox>
              <Checkbox value={12}>性功能障碍</Checkbox>
            </Checkbox.Group>
          </Form.Item>
          <Form.Item
            label="状态"
            name="status"
            valuePropName="checked"
            hidden
          >
            <Switch />
          </Form.Item>
          <Form.Item
            label="总是"
            name="always"
            valuePropName="checked"
            hidden
          >
            <Checkbox defaultChecked={false} />
          </Form.Item>
          <Form.Item
            label="经常"
            name="often"
            valuePropName="checked"
            hidden
          >
            <Checkbox defaultChecked={false} />
          </Form.Item>
          <Form.Item
            label="偶尔"
            name="sometimes"
            valuePropName="checked"
            hidden
          >
            <Checkbox defaultChecked={false} />
          </Form.Item>
          <Form.Item
            label="几乎不"
            name="hardly"
            valuePropName="checked"
            hidden
          >
            <Checkbox defaultChecked={false} />
          </Form.Item>
          <Form.Item
            label="没有"
            name="none"
            valuePropName="checked"
            hidden
          >
            <Checkbox defaultChecked={false} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 删除确认弹窗 */}
      <Modal
        open={isDeleteModalOpen}
        title="确认删除"
        onOk={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
        okText="确认"
        cancelText="取消"
      >
        <p>确认删除该试题吗？</p>
      </Modal>
    </Layout>
  );
};

export default Test;